package com.foreverwin.mes.common.service.impl;

import com.foreverwin.mes.common.dto.PrintDto;
import com.foreverwin.mes.common.model.PrintLog;
import com.foreverwin.mes.common.model.PrintRequest;
import com.foreverwin.mes.common.service.PrintLogService;
import com.foreverwin.mes.common.service.PrintService;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.foreverwin.mes.core.utils.HttpUtil;
import com.foreverwin.mes.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @author Ervin Chen
 * @date 2020/3/6 13:38
 */
@Service
public class PrintServiceImpl implements PrintService {

    @Value("${print.server}")
    private String printServer;

    @Autowired
    private PrintLogService printLogService;

    @Override
    public void print(PrintDto printDto) {
        String site = CommonMethods.getSite();
        String userBo = CommonMethods.getUserBo();
        Date now = new Date();

        PrintRequest printRequest = printDto.getPrintRequest();
        String isReprint = printDto.getIsReprint();
        String printer = printRequest.getPrinter();
        String printTemplate = printRequest.getTemplate();
        int labelQty = printRequest.getLabelQty();

        if (StringUtils.isBlank(printer)) {
            throw BusinessException.build("common.print.printerNotBlank", new Object[]{});
        }
        if (StringUtils.isBlank(printTemplate)) {
            throw BusinessException.build("common.print.printTemplateNotBlank", new Object[]{});
        }
        if (labelQty <= 0) {
            throw BusinessException.build("common.print.labelQtyNotValid", labelQty);
        }

        //ResponseEntity responseEntity = HttpUtil.callPost(printServer, "REQUEST_DATA=" + printRequest.toString());

        PrintLog printLog = new PrintLog();
        printLog.setHandle(UUID.randomUUID().toString());
        printLog.setSite(site);
        printLog.setPrinter(printer);
        printLog.setPrintParam(printRequest.toString());
        printLog.setPrintServer(printServer);
        printLog.setPrintTemplate(printTemplate);
        printLog.setIsReprint(isReprint);
        //printLog.setStatus(responseEntity.getStatusCode().toString());
        printLog.setStatus("200");
        printLog.setCreateUserBo(userBo);
        printLog.setCreatedDateTime(now);
        printLogService.insert(printLog);
    }
}
